function isNumber(value) {
    return!isNaN(parseFloat(value)) && Number.isFinite(Number(value));
}
export function groupAndCompute(groupKey, comValue, data) {
    const result = {};

    // 辅助函数，用于计算分组内的统计值
    function calculateGroupStats(groupItems) {
        const stats = {};
        comValue.forEach(val => {
            const [key, operation = 'sum'] = val.split(':');
            let values = [];
            for (let item of groupItems) {
                if (isNumber(item[key])) {
                    values.push(Number(item[key]))
                }
            }
            if (values.length === 0) {
                // 如果没有有效值，则设置为 undefined 或其他适当值
                for (let i = 0; i < groupItems.length; i++) {
                    if(groupItems[i][key] != undefined){
                        stats[key] = groupItems[i][key];
                        break
                    }
                }
            } else {
                switch (operation.toLowerCase()) {
                    case 'sum':
                        stats[key] = values.reduce((a, b) => a + b, 0).toFixed(3);
                        break;
                    case 'avg':
                        stats[key] = (values.reduce((a, b) => a + b, 0) / values.length).toFixed(3);
                        break;
                    case 'max':
                        stats[key] = Math.max(...values).toFixed(3);
                        break;
                    case 'min':
                        stats[key] = Math.min(...values).toFixed(3);
                        break;
                    default:
                        throw new Error(`Unsupported operation: ${operation}`);
                }
            }
        });
        return stats;
    }

    data.forEach(item => {
        const groupKeyStr = groupKey.map(key => item[key]).join('|');

        if (!result[groupKeyStr]) {
            result[groupKeyStr] = [];
        }

        result[groupKeyStr].push(item);
    });

    // 转换结果为所需格式
    return Object.values(result).map(groupItems => {
        const groupStats = calculateGroupStats(groupItems);
        const group = {};
        groupKey.forEach(key => {
            // 取分组中第一项的分组键值作为代表（假设所有项在分组键上都是相同的）
            group[key] = groupItems[0][key];
        });
        return { ...group, ...groupStats };
    });
}
